package cn._2dland.sakushi.client;

import java.util.ArrayList;
import java.util.List;

//import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import cn._2dland.http.HttpClient;
import cn._2dland.http.HttpStatus;
import cn._2dland.http.method.GetMethod;
import cn._2dland.http.method.PostMethod;
import cn._2dland.http.method.multiparts.FilePart;
import cn._2dland.http.method.multiparts.StringPart;
import cn._2dland.oauth.OAuthClient;
import cn._2dland.sakushi.SakushiInfo;
import cn._2dland.util.Base64;

/**
 * 饭否客户端类
 * 对饭否的API进行封装
 * 
 * @author deadblue
 */
public class FanfouClient {
	/** 饭否机器人UA识别 */
	private static final String USER_AGENT = "FanfouBot";

	/** 获取消息API */
	private static final String MENTION_URL = "http://api.fanfou.com/statuses/replies.json";
	/** 发布消息API */
	private static final String UPDATE_URL = "http://api.fanfou.com/statuses/update.json";
	/** 上传图片API */
	private static final String UPLOAD_URL = "http://api.fanfou.com/photos/upload.json";
	/** 获取私信API */
	private static final String MESSAGE_GET_URL = "http://api.fanfou.com/direct_messages.json";
	/** 发送私信API */
	private static final String MESSAGE_SEND_URL = "http://api.fanfou.com/direct_messages/new.json";

	/** HttpClient对象 */
	private HttpClient client = null;

	/**
	 * 饭否客户端构造器
	 */
	public FanfouClient() {
		client = new HttpClient();
		client.getClientParams().setUserAgent(USER_AGENT);
		client.getClientParams().setClientCharset("utf-8");
	}

	/**
	 * 饭否客户端构造器
	 * 
	 * @param user 用户名
	 * @param pass 密码
	 */
	public FanfouClient(String user, String pass) {
		String auth = user + ":" +  pass;
		auth = "Basic " + Base64.encode(auth.getBytes());

		// 初始化Http客户端
		client = new HttpClient();
		client.getClientParams().setUserAgent(USER_AGENT);
		client.getClientParams().setClientCharset("utf-8");
		client.addHeader("Authorization", auth);
	}

	/**
	 * 
	 * @param apiKey 应用的API Key
	 * @param token 访问令牌
	 * @param secret 签名密钥
	 */
	public FanfouClient(String apiKey, String token, String secret) {
		// 初始化Http客户端
		client = new OAuthClient(apiKey, token, secret);
		client.getClientParams().setUserAgent(USER_AGENT);
		client.getClientParams().setClientCharset("utf-8");
		//client.addHeader("Authorization", auth);
	}

	/**
	 * 读取通知消息
	 * @param sinceID
	 * @return
	 */
	public List<Mention> getMentions(String sinceID) {
		List<Mention> mentions = new ArrayList<Mention>();

		GetMethod get = new GetMethod(MENTION_URL);
		if(sinceID != null) {
			get.addParameter("since_id", sinceID);
		}

		try {
			// 获取发送结果
			int respCode = client.executeMethod(get);
			if(respCode != HttpStatus.SC_OK)
				throw new Exception("读取失败！");
			
			// 读取结果
			String jstr = get.getResponseString();
			JSONArray jarr = new JSONArray(jstr);

			// 解析并填充mentions数组
			for(int i=0; i<jarr.length(); i++) {
				Mention mention = new Mention();

				// 消息信息
				JSONObject menObj = jarr.getJSONObject(i);
				mention.setStatusId(menObj.getString("id"));
				mention.setSourceId(menObj.getString("in_reply_to_status_id"));

				// 获取并处理状态内容
				String text = menObj.getString("text");
				text = text.replaceAll("^@"+SakushiInfo.FANFOU_NAME+"\\s", "");
				text = text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&amp;", "&");
				mention.setText(text);

				// 发送者用户信息
				JSONObject userObj = menObj.getJSONObject("user");
				mention.setUserId(userObj.getString("id"));
				mention.setUserName(userObj.getString("name"));

				mentions.add(mention);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return mentions;
	}

	/**
	 * 读取私信
	 * @param sinceID
	 * @return
	 */
	public List<Mention> getMessages(String sinceID) {
		String url = MESSAGE_GET_URL;
		url += sinceID==null ? "" : "?since_id="+sinceID;

		GetMethod get = new GetMethod(url);
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送私信
	 * @param user 目标用户
	 * @param text 私信内容
	 * @param source 
	 * @return 发布结果
	 */
	public String send(String user, String text, String source) throws Exception {
		String url = MESSAGE_SEND_URL;
		PostMethod post = new PostMethod(url);
		try {
			
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	/**
	 * 发布状态
	 * 
	 * @param feed 状态信息
	 * @param location
	 * @param source
	 * @return 发布结果
	 */
	public String update(String feed, String location, String source) throws Exception {
		String result = null;

		PostMethod post = new PostMethod(UPDATE_URL);
		try {
			post.addParameter("status", feed);
			if(source != null) {
				post.addParameter("source", source);
			}
			if(location != null) {
				post.addParameter("location", location);
			}

			// 获取发送结果
			int respCode = client.executeMethod(post);
			if(respCode != HttpStatus.SC_OK)
				throw new Exception("发布失败！" + respCode);

			// 读取结果
			result = post.getResponseString();
			//JSONObject jsonObj = new JSONObject(jstr);
		}
		finally {
			post.releaseConnection();
		}

		return result;
	}

	/**
	 * 发布图片
	 * @param feed 图片描述
	 * @param image 图片字节组
	 * @param location 
	 * @param source
	 * @return
	 */
	public String upload(String feed, byte[] image, String location, String source) throws Exception {
		String result = null;
		PostMethod post = new PostMethod(UPLOAD_URL);
		try {
			// 以分段的方式添加参数
			post.addPart(new StringPart("status", feed));
			if(source != null) {
				post.addPart(new StringPart("source", source));
			}
			if(location != null) {
				post.addPart(new StringPart("location", location));
			}

			// 添加图片
			FilePart fp = new FilePart("photo", "image/png", "chart.png");
			fp.readBytes(image);
			post.addPart(fp);
			
			// 获取发送结果
			int respCode = client.executeMethod(post);
			if(respCode != HttpStatus.SC_OK)
				throw new Exception("发布失败！");

			// 读取结果
			result = post.getResponseString();
		}
		finally {
			post.releaseConnection();
		}
		return result;
	}
}
